import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import User from './components/User.vue'
import Link from './components/Link.vue'
import Tran from './components/Tran.vue'
import Task from './components/Task.vue'

// 定义路由
const routes = [
    { path: '/', name: 'login', component: Login },
    {
        path: '/home',
        name: 'home',
        component: Home,
        children: [
            { path: 'user', name: 'user', component: User },
            { path: 'link', name: 'link', component: Link },
            { path: 'tran', name: 'tran', component: Tran },
            { path: 'task', name: 'task', component: Task },
        ],
        meta: { auth: true }
    },
]

// 创建路由
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 守卫路由
router.beforeEach((to, from) => {
    // 鉴权
    if (to.meta.auth && to.name != 'login') {
        if (!sessionStorage.getItem('token')) {
            console.log(`router.beforeEach => unauthorized component redirect to ${to.name}`)
            return { name: 'login' }
        }
    }
    console.log(`router.beforeEach => route[${from.name} --> ${to.name}]`)
})

export default router

